package org.openrbac.rbac.service.impl;

import lombok.AllArgsConstructor;
import org.openrbac.rbac.entity.Auth;
import org.openrbac.rbac.entity.Role;
import org.openrbac.rbac.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.Objects;

/**
 * @author bapie
 */
@Service
@AllArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        org.openrbac.rbac.entity.User user = userService.getUser(username);
        System.out.println(user);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        LinkedList<GrantedAuthority> authorities = new LinkedList<>();
        for (Role role : userService.findRoles(username)) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRolename()));
        }
        for (Auth auth : userService.findAuths(username)) {
            authorities.add(new SimpleGrantedAuthority(auth.getUri()));
        }
        return User.withUsername(username).authorities(authorities).password(user.getPassword()).build();
    }
}
